package com.aly.beanValidate.core.validator;

import com.aly.beanValidate.core.GlobalConfigs;
import com.aly.game.util.cls.ClassUtils;
import org.dom4j.Element;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CheckValidators {
    private static Map<String, Constructor<? extends CheckValidator>> allValidators = new HashMap<>();
    static {
        String pkg = CheckValidators.class.getPackage().getName() + ".impl";
        List<Class<? extends CheckValidator>> all = ClassUtils.getAllClass(CheckValidator.class, pkg);
        for (Class<? extends CheckValidator> clazz : all) {
            if (Modifier.isAbstract(clazz.getModifiers())) {
                continue;
            }
            Name name = clazz.getAnnotation(Name.class);
            try {
                Constructor<? extends CheckValidator> constructor = clazz.getDeclaredConstructor(Element.class, GlobalConfigs.class);
                constructor.setAccessible(true);
                allValidators.put(name.value(), constructor);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static CheckValidator create(Element element, GlobalConfigs globalConfigs) throws Exception{
        Constructor<? extends CheckValidator> constructor = allValidators.get(element.getName());
        return constructor.newInstance(element, globalConfigs);
    }
}
